<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <!-- 元数据和标题 -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>可爱 2048 游戏</title>

    <!-- 样式表 -->
    <style>
        body {
            background-color: #faf8ef;
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            margin: 0;
        }

        #header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 90%;
            max-width: 500px;
            color: #776e65;
        }

        h1 {
            margin: 0;
        }

        #score-board {
            display: flex;
            gap: 10px;
        }

        #score,
        #high-score {
            background-color: #bbada0;
            color: white;
            padding: 5px 10px;
            border-radius: 5px;
        }

        #game-board {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            grid-template-rows: repeat(4, 1fr);
            gap: 10px;
            background-color: #bbada0;
            padding: 10px;
            border-radius: 5px;
            width: 90%;
            max-width: 500px;
            margin: 20px 0;
        }

        .cell {
            background-color: rgba(238, 228, 218, 0.35);
            border-radius: 5px;
            aspect-ratio: 1/1;
        }

        .tile {
            width: 100%;
            height: 100%;
            background-size: cover;
            border-radius: 5px;
        }

        #game-rules {
            text-align: left;
            color: #776e65;
            width: 90%;
            max-width: 500px;
            font-size: 14px;
        }

        #win-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            align-items: center;
            justify-content: center;
        }

        #win-modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            text-align: center;
        }
    </style>
</head>

<body>
    <!-- 游戏头部，包含标题和得分板 -->
    <div id="header">
        <h1>可爱 2048 游戏</h1>
        <div id="score-board">
            <div id="score">得分: 0</div>
            <div id="high-score">最高分: 0</div>
        </div>
    </div>

    <!-- 游戏棋盘 -->
    <div id="game-board"></div>

    <!-- 游戏规则 -->
    <div id="game-rules">
        <p>游戏规则：使用键盘方向键（上、下、左、右）控制卡片移动，相同的卡片会合并成一个数值更大的卡片，目标是合并出数值为 2048 的卡片。</p>
    </div>

    <!-- 胜利弹窗 -->
    <div id="win-modal">
        <div id="win-modal-content">
            <p>恭喜你已经合并了一只宇宙无敌最可爱的猫咪</p>
            <button onclick="closeWinModal()">确认</button>
        </div>
    </div>

    <!-- 游戏逻辑脚本 -->
    <script>
        // 获取 DOM 元素
        const gameBoard = document.getElementById('game-board');
        const winModal = document.getElementById('win-modal');
        const scoreElement = document.getElementById('score');
        const highScoreElement = document.getElementById('high-score');

        // 定义猫咪图片链接
        const images = {
            2: 'https://p9-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/df099f209335f8b25e1d4ab9ce2867ff_1741677321668230149.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1773213321&x-signature=reNM%2F907NNX7Rc%2BE4FflYbWaRKo%3D',
            4: 'https://p9-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/322b9826909d14458d22e0931fd06aac_1741677330491084517.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1773213330&x-signature=a1ptVuhTOwjrpRZSdnL%2FUKYV9MY%3D',
            8: 'https://p3-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/1a563d103b7496a5b9eb365ff9ea58bd_1741677409407029394.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1773213409&x-signature=L0drmZ0N1Z2%2BjUD9g9gcP0Nn7TM%3D',
            16: 'https://p3-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/f51aebc9e6d5eee19fc026e3f1070185_1741677412756659826.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1773213412&x-signature=%2F%2FMLyi7m%2Bu%2Fo%2F%2FTQeYqmUWeDtLQ%3D',
            32: 'https://p3-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/8693822e52091fd6896366ae4e922bc2_1741677429462075923.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1773213429&x-signature=tLOJO0F5DKTLStoKnja6l2fr%2FOg%3D',
            64: 'https://p3-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/5fbb02d79c0f16f69ec86ea7a83d7e36_1741677431738410576.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1773213431&x-signature=Ry8L%2FkXszOCFFHkMeIdKm6Ktg%2FQ%3D',
            128: 'https://p3-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/f2c91103fc53286b5d481390c12d665f_1741677444595987213.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1773213444&x-signature=X5AHPsnNLXS25hlANqlvTtpSQmc%3D',
            256: 'https://p9-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/9f4e790544e519f8c110d2c73e7b03bf_1741677446066399364.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1773213446&x-signature=DmV9R3QrONwWz%2F4fUnoceUjiU8E%3D',
            512: 'https://p3-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/8f72db8a79741930894920bc8faced83_1741677458934448994.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1773213458&x-signature=YxMhmlrT%2FY7brkyal9u5oaifd3g%3D',
            1024: 'https://p3-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/f565fa57b977fa953208f7a2b4edd839_1741677459756646895.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1773213459&x-signature=r0bBAR7T7NVF3dyu1aGI%2FlWfR4w%3D',
            2048: 'https://p3-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/dbb80e7d3948b8af02664915eeee38d2_1741677502512862779.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1773213502&x-signature=Bv%2FEdGFqr%2Bq47a8g1D4KiU9XYqQ%3D'
        };

        // 初始化游戏棋盘和得分
        let board = [
            [0, 0, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 0]
        ];
        let score = 0;
        let highScore = localStorage.getItem('highScore')? parseInt(localStorage.getItem('highScore')) : 0;
        highScoreElement.textContent = `最高分: ${highScore}`;

        // 创建游戏棋盘
        function createBoard() {
            gameBoard.innerHTML = '';
            for (let i = 0; i < 4; i++) {
                for (let j = 0; j < 4; j++) {
                    const cell = document.createElement('div');
                    cell.classList.add('cell');
                    if (board[i][j]!== 0) {
                        const tile = document.createElement('div');
                        tile.classList.add('tile');
                        tile.style.backgroundImage = `url(${images[board[i][j]]})`;
                        cell.appendChild(tile);
                    }
                    gameBoard.appendChild(cell);
                }
            }
            scoreElement.textContent = `得分: ${score}`;
        }

        // 添加随机方块
        function addRandomTile() {
            const emptyCells = [];
            for (let i = 0; i < 4; i++) {
                for (let j = 0; j < 4; j++) {
                    if (board[i][j] === 0) {
                        emptyCells.push({ i, j });
                    }
                }
            }
            if (emptyCells.length > 0) {
                const randomIndex = Math.floor(Math.random() * emptyCells.length);
                const { i, j } = emptyCells[randomIndex];
                board[i][j] = Math.random() < 0.9? 2 : 4;
            }
        }

        // 合并方块
        function mergeTiles(row) {
            let newRow = row.filter(tile => tile!== 0);
            for (let i = 0; i < newRow.length - 1; i++) {
                if (newRow[i] === newRow[i + 1]) {
                    newRow[i] *= 2;
                    score += newRow[i];
                    if (newRow[i] === 2048) {
                        showWinModal();
                    }
                    newRow[i + 1] = 0;
                }
            }
            newRow = newRow.filter(tile => tile!== 0);
            while (newRow.length < 4) {
                newRow.push(0);
            }
            return newRow;
        }

        // 向左移动
        function moveLeft() {
            let moved = false;
            for (let i = 0; i < 4; i++) {
                const oldRow = [...board[i]];
                board[i] = mergeTiles(board[i]);
                if (oldRow.join(',')!== board[i].join(',')) {
                    moved = true;
                }
            }
            if (moved) {
                addRandomTile();
            }
            updateScore();
            createBoard();
        }

        // 向右移动
        function moveRight() {
            let moved = false;
            for (let i = 0; i < 4; i++) {
                const oldRow = [...board[i]];
                const reversedRow = board[i].slice().reverse();
                const newReversedRow = mergeTiles(reversedRow);
                board[i] = newReversedRow.reverse();
                if (oldRow.join(',')!== board[i].join(',')) {
                    moved = true;
                }
            }
            if (moved) {
                addRandomTile();
            }
            updateScore();
            createBoard();
        }

        // 向上移动
        function moveUp() {
            let moved = false;
            for (let j = 0; j < 4; j++) {
                const column = [];
                for (let i = 0; i < 4; i++) {
                    column.push(board[i][j]);
                }
                const oldColumn = [...column];
                const newColumn = mergeTiles(column);
                for (let i = 0; i < 4; i++) {
                    board[i][j] = newColumn[i];
                }
                if (oldColumn.join(',')!== newColumn.join(',')) {
                    moved = true;
                }
            }
            if (moved) {
                addRandomTile();
            }
            updateScore();
            createBoard();
        }

        // 向下移动
        function moveDown() {
            let moved = false;
            for (let j = 0; j < 4; j++) {
                const column = [];
                for (let i = 0; i < 4; i++) {
                    column.push(board[i][j]);
                }
                const oldColumn = [...column];
                const reversedColumn = column.slice().reverse();
                const newReversedColumn = mergeTiles(reversedColumn);
                const newColumn = newReversedColumn.reverse();
                for (let i = 0; i < 4; i++) {
                    board[i][j] = newColumn[i];
                }
                if (oldColumn.join(',')!== newColumn.join(',')) {
                    moved = true;
                }
            }
            if (moved) {
                addRandomTile();
            }
            updateScore();
            createBoard();
        }

        // 处理键盘事件
        function handleKeyPress(event) {
            switch (event.key) {
                case 'ArrowLeft':
                    moveLeft();
                    break;
                case 'ArrowRight':
                    moveRight();
                    break;
                case 'ArrowUp':
                    moveUp();
                    break;
                case 'ArrowDown':
                    moveDown();
                    break;
            }
        }

        // 显示胜利弹窗
        function showWinModal() {
            winModal.style.display = 'flex';
        }

        // 关闭胜利弹窗
        function closeWinModal() {
            winModal.style.display = 'none';
        }

        // 更新得分
        function updateScore() {
            if (score > highScore) {
                highScore = score;
                highScoreElement.textContent = `最高分: ${highScore}`;
                localStorage.setItem('highScore', highScore);
            }
            scoreElement.textContent = `得分: ${score}`;
        }

        // 监听键盘事件并初始化游戏
        window.addEventListener('keydown', handleKeyPress);

        addRandomTile();
        addRandomTile();
        createBoard();
    </script>
</body>

</html>